#include "Socket.hpp"
#include "Protocol.hpp"
#include "Calculate.hpp"

using namespace NetWork;
using namespace Protocol;
using namespace CalculateNS;
using namespace std;

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        cout << "Usage: " << argv[0] << " server_ip server_port" << endl;
        return 1;
    }

    string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    Socket* client = new TcpSocket();
    if(!client->BuildConnectSocketMethod(server_ip, server_port))
    {
        cerr << "Connect to server failed." << endl;
        return -1;
    }
    cout << "Connect to server:[" << server_ip << ":" << server_port << "] success." << endl;

    Factory factory;

    while(true)
    {
        string data;
        std::cout << "please input message# ";
        std::getline(std::cin, data);

        // 1. send request to server
        string encoded_data = PacketHandler::Encode(data);
        client->Send(encoded_data);
        if(data == "quit")
        {
            break;
        }
        // 2. get response from server
        std::string response_data;
        client->Recv(&response_data, 1024);
        std::string decoded_data;
        if(PacketHandler::Decode(response_data, &decoded_data))
        {
            auto resp = factory.CreateCalResponse();
            auto col_resp = std::dynamic_pointer_cast<Cal_Response>(resp);
            col_resp->Deserialize(decoded_data);
            if(col_resp->GetErrorCode() == 0)
            {
                cout << "Get result from server: " << col_resp->GetResult() << endl;
            }
            else
            {
                cout << "Get error from server: " << col_resp->GetErrorCode() << endl;
            }
        }
    }

    client->CloseSocket();

    return 0;
}